package com.lhj.library.application.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSON;
import com.google.common.base.Preconditions;
import com.lhj.library.application.convert.UserDtoConverter;
import com.lhj.library.application.dto.AuthDTO;
import com.lhj.library.common.entity.Result;
import com.lhj.library.domain.entity.UserBO;
import com.lhj.library.domain.service.AuthDomainService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * 登录鉴权控制器
 */
@RestController
@RequestMapping("/auth")
@Slf4j
public class AuthController {

    @Resource
    private AuthDomainService authDomainService;

    /**
     * 用户注册
     *
     * @param authDTO
     * @return
     */
    @PostMapping("/register")
    public Result<Boolean> register(@RequestBody AuthDTO authDTO) {
        try {
            if (log.isInfoEnabled()) {
                log.info("AuthController.register.dto:{}", JSON.toJSONString(authDTO));
            }
            Preconditions.checkNotNull(authDTO.getPassword(), "密码不能为空");
            Preconditions.checkNotNull(authDTO.getStudentId(), "学号不能为空");
            UserBO userBO = UserDtoConverter.INSTANCE.convertAuthDtoToUserBo(authDTO);
            return Result.ok(authDomainService.register(userBO));
        } catch (Exception e) {
            return Result.fail("注册失败");
        }
    }

    /**
     * 用户登录
     *
     * @param authDTO
     * @return
     */
    @PostMapping("login")
    public Result<String> login(@RequestBody AuthDTO authDTO) {
        try {
            if (log.isInfoEnabled()) {
                log.info("AuthController.login.dto:{}", JSON.toJSONString(authDTO));
            }
            Preconditions.checkNotNull(authDTO.getStudentId(), "学号不能为空");
            Preconditions.checkNotNull(authDTO.getPassword(), "密码不能为空");
            UserBO userBO = UserDtoConverter.INSTANCE.convertAuthDtoToUserBo(authDTO);
            authDomainService.login(userBO);
            return Result.ok("登录成功");
        } catch (Exception e) {
            return Result.fail("登录失败");
        }
    }

    // 查询登录状态，浏览器访问： http://localhost:8081/user/isLogin
    @GetMapping("isLogin")
    public String isLogin() {
        return "当前会话是否登录：" + StpUtil.isLogin();
    }
}
